package com.yuexunit.finance.project.action.v1;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yuexunit.core.BusinessException;
import com.yuexunit.core.ConfigPropertites;
import com.yuexunit.finance.common.httpclient.HttpClientHelper;
import com.yuexunit.finance.common.util.BeanUtils;
import com.yuexunit.finance.project.action.v1.model.FinanceContainerBill;
import com.yuexunit.finance.project.action.v1.model.OrderInfo;
import com.yuexunit.finance.project.action.v1.model.OrderInfoDetail;
import com.yuexunit.finance.project.action.v1.model.OrderInfoResult;
import com.yuexunit.finance.project.entity.FinanceApplicationEntity;
import com.yuexunit.finance.project.entity.FinanceAuditEntity;
import com.yuexunit.finance.project.entity.FinanceBulkstockEntity;
import com.yuexunit.finance.project.entity.FinanceContainerBillEntity;
import com.yuexunit.finance.project.entity.FinanceContainerEntity;
import com.yuexunit.finance.project.entity.lexicon.ContainerSourceEnum;
import com.yuexunit.finance.project.service.FinanceApplicationService;
import com.yuexunit.finance.project.service.FinanceAuditService;
import com.yuexunit.finance.project.service.FinanceBulkstockService;
import com.yuexunit.finance.project.service.FinanceContainerBillService;
import com.yuexunit.finance.project.service.FinanceContainerService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.jsonutil.JSON;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.StringUtil;


/**
 * @author wenwenlong
 */
@Implements(FinanceContainerBillActionApi.class)
public class FinanceContainerBillActionApiImpl implements FinanceContainerBillActionApi{
	private FinanceContainerBillService financeContainerBillService = ComponentFactory.loadClass(FinanceContainerBillService.class);
	private FinanceContainerService financeContainerService = ComponentFactory.loadClass(FinanceContainerService.class);
	private FinanceApplicationService financeApplicationService = ComponentFactory.loadClass(FinanceApplicationService.class);
	private FinanceBulkstockService financeBulkstockService = ComponentFactory.loadClass(FinanceBulkstockService.class);
	FinanceAuditService financeAuditService = ComponentFactory.loadClass(FinanceAuditService.class);

	@Override
	@Transactional
	public String createFinanceContainerBill(Long financeId, String model, String dimension, String emptyWeight, Integer quantity, Boolean soc, Long recieveNoticeId) {
		FinanceContainerBillEntity entity = new FinanceContainerBillEntity();
		if (financeId == null) {
			entity.setContainerSource(ContainerSourceEnum.LOGISTICS);
			entity.setRecieveNoticeId(recieveNoticeId);
			entity.setModel(model);
			entity.setDimension(dimension);
			entity.setEmptyWeight(BigDecimal.ZERO);
			entity.setQuantity(quantity);
			entity.setSoc(soc);
		} else {
			entity.setContainerSource(ContainerSourceEnum.PLATFORM);
			entity.setFinanceId(financeId);
			entity.setModel(model);
			entity.setDimension(dimension);
			entity.setEmptyWeight(BigDecimal.ZERO);
			entity.setQuantity(quantity);
			entity.setSoc(soc);
			
			FinanceContainerEntity financeContainerEntity = financeContainerService.inquireFinanceContainer(financeId);
			financeContainerEntity.setCaseQuantity(financeContainerEntity.getCaseQuantity() + quantity);
			financeContainerService.renovateFinanceContainer(financeContainerEntity);
		}
		financeContainerBillService.createFinanceContainerBill(entity);
		return entity.getContainerBillId().toString();
	}
	
	@Override
	@Transactional
	public OrderInfoResult createOrderInfo(Long financeId) {
		FinanceApplicationEntity finance = financeApplicationService.inquireFinanceApplicationEntity(financeId);
		List<FinanceBulkstockEntity> bulkstocks = financeBulkstockService.inquireFinanceBulkstockList(financeId);
		FinanceAuditEntity financeAudit = financeAuditService.inquireLatestFinanceAudit(financeId);
		List<FinanceContainerBillEntity> containerBills = financeContainerBillService.inquireFinanceContainerBillList(financeId);
		String url = ConfigPropertites.getProperties("trace.goods.commitPO");
		OrderInfoResult result = new OrderInfoResult();
		FinanceContainerEntity persist = financeContainerService.inquireFinanceContainer(financeId);
		
		if (StringUtil.isNotBlank(persist.getBookingSpaceNumber())) {
			throw new BusinessException("该融资已订过舱！");
		}
		
		if (containerBills == null) {
			throw new BusinessException("没有订箱信息，不能订舱！");
		}
		
		if (!bulkstocks.isEmpty()) {
			FinanceBulkstockEntity fbe = bulkstocks.get(0);
			OrderInfo oi = new OrderInfo();
			oi.setFromPort(finance.getDeliverAddress());
			oi.setToPort(finance.getReceiveAddress());
			oi.setChangeShip("0");
			oi.setNoteDelivery("0");
			oi.setPreNote("0");
			oi.setGoodsNO(fbe.getBulkstockNumber());
			oi.setGoodsName(fbe.getBulkstockName());
			oi.setGoodsQuantity(fbe.getQuantity().toString());
			oi.setGoodsWeight(fbe.getWeight().toString());
			oi.setGoodsVolume(fbe.getVolume().toString());
			if (fbe.getDangerous()) {
				oi.setIsDanger("1");
				oi.setIMDG(fbe.getBulkstockDangerous().getImdg());
				oi.setUNNO(fbe.getBulkstockDangerous().getUnNum());
			} else {
				oi.setIsDanger("0");
			}
			
			if (fbe.getColdStorage()) {
				oi.setIsFrozen("1");
				oi.setTempUnit(fbe.getBulkstockColdStorage().getTempUnit());
				oi.setTemp(fbe.getBulkstockColdStorage().getSetTemperature().toString());
				oi.setWind(fbe.getBulkstockColdStorage().getVent().toString());
				oi.setTempRange(fbe.getBulkstockColdStorage().getTempMin() + "~" + fbe.getBulkstockColdStorage().getTempMax());
			} else {
				oi.setIsFrozen("0");
			}
			
			if (financeAudit != null) {
				oi.setIsInsurance("1");
				oi.setInsurPrice(financeAudit.getForceAmount().toString());
			} else {
				oi.setIsInsurance("0");
			}
			
			List<OrderInfoDetail> details = new ArrayList<>();
			for (FinanceContainerBillEntity fcbe : containerBills) {
				OrderInfoDetail detail = new OrderInfoDetail();
				detail.setBoxType(fcbe.getModel());
				detail.setQuantity(fcbe.getQuantity().toString());
				details.add(detail);
			}
			
			Map<String, String> params = new HashMap<>();
			params.put("POHead", JSON.toString(oi));
			params.put("POBody", JSON.toString(details));
			
			String responseText = HttpClientHelper.post(url, params);
			if (responseText == null) {
				throw new BusinessException("订舱失败！");
			}
			
			result = JSON.toBean(responseText, OrderInfoResult.class);
			
			if (result.getPONO() == null) {
				throw new BusinessException("订舱失败！");
			}
			
			if (persist == null || persist.getFinanceId() == 0) {
				FinanceContainerEntity entity = new FinanceContainerEntity();
				entity.setFinanceId(financeId);
				entity.setBookingSpaceNumber(result.getPONO());
				entity.setEnterpriseId(finance.getEnterpriseId());
				entity.setEnterpriseName(finance.getEnterpriseName());
				financeContainerService.createFinanceContainer(entity);
			} else {
				persist.setBookingSpaceNumber(result.getPONO());
				financeContainerService.renovateFinanceContainer(persist);
			}
		}
		
		return result;
	}

	@Override
	@Transactional
	public void deleteFinanceContainerBill(Long containerBillId) {
		FinanceContainerBillEntity entity = financeContainerBillService.inquireFinanceContainerBillDetail(containerBillId);
		if(entity.getContainerSource() == ContainerSourceEnum.ENTERPRISE) {
			throw new BusinessException("用户订舱信息无法删除！");
		}
		
		FinanceContainerEntity financeContainerEntity = financeContainerService.inquireFinanceContainer(entity.getFinanceId());
		financeContainerEntity.setCaseQuantity(financeContainerEntity.getCaseQuantity() - entity.getQuantity());
		financeContainerService.renovateFinanceContainer(financeContainerEntity);
		
		financeContainerBillService.deleteFinanceContainerBill(entity);
	}

	@Override
	public List<FinanceContainerBill> inquireFinanceContainerBillList(Long recieveNoticeId) {
		List<FinanceContainerBillEntity> containerBills = financeContainerBillService.inquireFinanceContainerBillListByNoticeId(recieveNoticeId);
		List<FinanceContainerBill> list = new ArrayList<FinanceContainerBill>();
		for (FinanceContainerBillEntity fcbe : containerBills) {
			FinanceContainerBill fcb = new FinanceContainerBill();
			BeanUtils.copyProperties(fcbe, fcb);
			fcb.setContainerSource(fcbe.getContainerSource().ordinal());
			list.add(fcb);
		}
		return list;
	}
}
